What is @reach/observe-rect?
@reach/observe-rect is a utility for observing changes to the size and position of a DOM element. It provides a simple API to track the dimensions and position of an element, which can be useful for responsive design, animations, and other dynamic UI updates.
What are @reach/observe-rect's main functionalities?
Observe changes to an element's size and position
This feature allows you to observe changes to the size and position of a DOM element. The `observeRect` function takes an element and a callback function that receives the new rect object whenever the element's size or position changes. The `unobserve` function can be called to stop observing.
const { observeRect } = require('@reach/observe-rect');
const element = document.getElementById('my-element');
const unobserve = observeRect(element, (rect) => {
console.log('Element rect:', rect);
});
// To stop observing
unobserve();
Other packages similar to @reach/observe-rect
resize-observer-polyfill
The `resize-observer-polyfill` package provides a polyfill for the ResizeObserver API, which allows you to observe changes to the dimensions of an element. It is similar to @reach/observe-rect but focuses solely on size changes and does not provide position information.
react-use-measure
The `react-use-measure` package is a React hook that allows you to measure the size of a DOM element. It is similar to @reach/observe-rect but is designed specifically for React applications and provides a hook-based API.
react-resize-detector
The `react-resize-detector` package is another React-specific library that provides a way to detect changes to the size of a DOM element. It is similar to @reach/observe-rect but is tailored for use with React components and provides a higher-level API.
Observe the rect of a DOM element.
Installation
npm install @reach/observe-rect
# or
yarn add @reach/observe-rect
Usage
import observeRect from "@reach/observe-rect";
let node = document.getElementById("some-node");
let rectObserver = observeRect(node, rect => {
console.log("left", rect.left);
console.log("top", rect.top);
console.log("height", rect.height);
console.log("width", rect.width);
});
rectObserver.observe();
rectObserver.unobserve();
About
A lot of things can change the position or size of an element, like scrolling, content reflows and user input. This utility observes and notifies you when your element's rect changes.
Legal
MIT License
Copyright (c) 2018-present, Ryan Florence